package com.jiefeng.manager.service.springsecurity;

import com.jiefeng.dao.security.RoleMapper;
import com.jiefeng.dao.security.UserMapper;
import com.jiefeng.dao.security.UserRoleMapper;
import com.jiefeng.manager.table.springsecurity.Role;
import com.jiefeng.manager.table.springsecurity.User;
import com.jiefeng.manager.table.springsecurity.UserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by WuZhiqi on 2016/7/4.
 */
@Service
public class UserRoleServiceDaoImpl implements UserRoleServiceDao{

    private static final Logger logger = LoggerFactory.getLogger(UserRoleServiceDaoImpl.class);

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public User queryUserByUsername(String username) {
        User user = userMapper.queryUserByUsername(username);
        if(null != user){
            List<UserRole> userRoleList = userRoleMapper.queryUserRoleByUserId(user.getId());
            List<Long> roleIds = new ArrayList<Long>();
            for(UserRole userRole : userRoleList){
                userRole.setUser(user);
                roleIds.add(userRole.getRole().getId());
            }
            List<Role> roleList = roleMapper.queryRolesByIds(roleIds);
            for(int i = 0 ; i < roleList.size(); i++){
                ;           userRoleList.get(i).setRole(roleList.get(i));
            }
            user.setUserRoles(userRoleList);
        }
        return user;
    }
}
